/**
 * 客户端测试1908接口脚本
 * 专注于测试：改名功能、改名卡消耗、事务控制
 */

const http = require('http');
const WebSocket = require('ws');

// 测试配置
const CONFIG = {
  server: {
    host: 'localhost',
    port: 3000,
    protocol: 'http'
  },
  testUser: {
    mobile: '17091271111',
    password: '123456',
    passwordHash: 'e10adc3949ba59abbe56e057f20f883e'
  },
  testCharacter: {
    name: '测试角色',
    sex: 1,
    roleType: 1,
    headIndex: 2
  },
  renameCardItemId: 78
};

class Code1908Tester {
  constructor() {
    this.token = null;
    this.userId = null;
    this.ws = null;
    this.characters = [];
    this.selectedCharacter = null;
    this.testResults = [];
    this.renameResults = [];
    this.originalCharacterName = null;
  }

  async runTest () {
    console.log('🚀 开始客户端1908接口测试...\n');
    console.log('测试目标：HTTP登录 → WebSocket连接 → 选择角色 → 改名功能测试 → 改名卡消耗验证 → 事务控制验证\n');

    try {
      await this.testHttpLogin();
      await this.testWebSocketConnection();
      await this.testQueryCharacters();

      if (this.characters.length === 0) {
        await this.testCreateCharacter();
        await this.testQueryCharacters();
      }

      await this.testSelectCharacter();
      await this.testCode1908NormalRename();
      await this.testCode1908NameWithSpace();
      await this.testCode1908EmptyName();
      await this.testCode1908DuplicateName();
      await this.testCode1908NoRenameCard();
      await this.validateRenameCardConsumption();
      await this.testDisconnect();
      this.printTestResults();
    } catch (error) {
      console.error('❌ 测试过程中发生错误:', error.message);
      this.addTestResult('整体测试', false, error.message);
    }
  }

  async testHttpLogin () {
    console.log('🔐 步骤1: HTTP登录测试...');
    try {
      await this.registerUser();
      const loginData = await this.makeHttpRequest('/user-service/user/login', 'POST', {
        mobile: CONFIG.testUser.mobile,
        pwd: CONFIG.testUser.passwordHash
      });

      if (loginData.code === 0 && loginData.data) {
        this.userId = 2001;
        this.token = loginData.data.accessToken;
        console.log(`✅ 登录成功: userId=${this.userId}, token=${this.token.substring(0, 8)}...`);
        this.addTestResult('HTTP登录', true, `用户ID: ${this.userId}`);
      } else {
        throw new Error(`登录失败: ${loginData.msg || '未知错误'}`);
      }
    } catch (error) {
      console.log('❌ 登录失败:', error.message);
      this.addTestResult('HTTP登录', false, error.message);
      throw error;
    }
  }

  async registerUser () {
    try {
      const res = await this.makeHttpRequest('/user-service/user/register', 'POST', {
        mobile: CONFIG.testUser.mobile,
        pwd: CONFIG.testUser.passwordHash,
        captcha: '123456'
      });
      console.log('📝 用户注册成功', res);
    } catch (error) {
      if (error.message.includes('MOBILE_EXISTS') || error.message.includes('已存在')) {
        console.log('👤 用户已存在，跳过注册');
      } else {
        console.log('⚠️ 注册失败:', error.message);
      }
    }
  }

  async testWebSocketConnection () {
    console.log('\n🔌 步骤2: WebSocket连接测试...');
    return new Promise((resolve, reject) => {
      try {
        const wsUrl = `ws://${CONFIG.server.host}:${CONFIG.server.port}/user-service/websocket?t=${this.token}`;
        this.ws = new WebSocket(wsUrl);

        this.ws.on('open', async () => {
          console.log('✅ WebSocket连接成功');
          this.addTestResult('WebSocket连接', true, '连接建立成功');
          this.setupMessageHandler();
          await this.delay(500);
          resolve();
        });

        this.ws.on('error', (error) => {
          console.log('❌ WebSocket连接失败:', error.message);
          this.addTestResult('WebSocket连接', false, error.message);
          reject(error);
        });

        this.ws.on('close', () => {
          console.log('🔌 WebSocket连接已关闭');
        });

        setTimeout(() => {
          if (this.ws.readyState === WebSocket.CONNECTING) {
            this.ws.close();
            reject(new Error('连接超时'));
          }
        }, 10000);
      } catch (error) {
        reject(error);
      }
    });
  }

  setupMessageHandler () {
    this.ws.on('message', (data) => {
      try {
        const message = JSON.parse(data.toString());
        console.log('📨 收到消息:', JSON.stringify(message, null, 2));
        this.handleWebSocketResponse(message);
      } catch (error) {
        console.error('❌ 消息解析失败:', error.message);
      }
    });
  }

  handleWebSocketResponse (message) {
    const { act_id, code, roleList, roleCount, data, msg } = message;

    switch (act_id) {
      case 3:
        if (roleList && Array.isArray(roleList)) {
          this.characters = roleList;
          console.log(`📋 获取到${roleCount || roleList.length}个角色`);
        }
        break;
      case 4:
        if (code === 0) {
          console.log('🎯 角色选择成功');
        }
        break;
      case 5:
      case 390:
        if (code === 0) {
          console.log('🆕 角色创建成功');
        }
        break;
      case 1908:
        this.renameResults.push({
          act_id: message.act_id,
          code: message.code,
          data: message.data,
          msg: message.msg,
          timestamp: new Date().toISOString()
        });
        console.log(`✏️ 改名功能响应:`, JSON.stringify(message, null, 2));
        break;
    }
  }

  async testQueryCharacters () {
    console.log('\n📋 步骤3: 查询角色列表...');
    return new Promise(async (resolve) => {
      if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
        this.addTestResult('查询角色列表', false, 'WebSocket未连接');
        resolve();
        return;
      }

      await this.delay(1000);

      const responseHandler = (data) => {
        try {
          const message = JSON.parse(data.toString());
          if (message.act_id === 3) {
            this.ws.removeListener('message', responseHandler);

            if (message.roleList && Array.isArray(message.roleList)) {
              this.characters = message.roleList;
              console.log(`✅ 查询成功，共${message.roleCount || message.roleList.length}个角色`);
              this.addTestResult('查询角色列表', true, `获取${this.characters.length}个角色`);
            } else {
              this.characters = [];
              console.log('✅ 查询成功，暂无角色');
              this.addTestResult('查询角色列表', true, '获取0个角色');
            }
            resolve();
          }
        } catch (error) {
          this.ws.removeListener('message', responseHandler);
          this.addTestResult('查询角色列表', false, '响应解析失败');
          resolve();
        }
      };

      this.ws.on('message', responseHandler);
      this.ws.send(JSON.stringify({ c: 3, d: null }));

      setTimeout(() => {
        this.ws.removeListener('message', responseHandler);
        this.addTestResult('查询角色列表', false, '请求超时');
        resolve();
      }, 10000);
    });
  }

  async testCreateCharacter () {
    console.log('\n🆕 步骤4: 创建角色测试...');
    if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
      this.addTestResult('创建角色', false, 'WebSocket未连接');
      return;
    }

    return new Promise((resolve) => {
      let responseReceived = false;
      let retryCount = 0;
      const maxRetries = 2;

      const responseHandler = (data) => {
        try {
          const message = JSON.parse(data.toString());
          console.log(`📨 收到创建角色响应:`, JSON.stringify(message, null, 2));

          if (message.act_id === 5 || message.act_id === 390) {
            this.ws.removeListener('message', responseHandler);
            responseReceived = true;

            if (message.code === 0) {
              console.log('✅ 角色创建成功');
              this.addTestResult('创建角色', true, '角色创建成功');
              setTimeout(() => resolve(), 2000);
            } else {
              const errorMsg = message.msg || '未知错误';
              console.log(`❌ 角色创建失败: ${errorMsg}`);

              if (errorMsg.includes('重复') || errorMsg.includes('已存在') || errorMsg.includes('DUPLICATE')) {
                if (retryCount < maxRetries) {
                  retryCount++;
                  const newName = `${CONFIG.testCharacter.name}_${Date.now()}`;
                  console.log(`🔄 角色名重复，尝试使用新名字: ${newName}`);
                  setTimeout(() => {
                    this.createCharacterWithName(newName, resolve);
                  }, 1000);
                  return;
                }
              }

              this.addTestResult('创建角色', false, errorMsg);
              resolve();
            }
          }
        } catch (error) {
          console.error('❌ 创建角色响应解析失败:', error.message);
          this.ws.removeListener('message', responseHandler);
          this.addTestResult('创建角色', false, '响应解析失败');
          resolve();
        }
      };

      this.ws.on('message', responseHandler);
      this.createCharacterWithName(CONFIG.testCharacter.name, resolve);

      setTimeout(() => {
        if (!responseReceived) {
          this.ws.removeListener('message', responseHandler);
          this.addTestResult('创建角色', false, '请求超时');
          resolve();
        }
      }, 15000);
    });
  }

  createCharacterWithName (name, resolve) {
    const createData = {
      c: 5,
      d: {
        name: name,
        sex: CONFIG.testCharacter.sex,
        roleType: CONFIG.testCharacter.roleType,
        headIndex: CONFIG.testCharacter.headIndex
      }
    };

    console.log(`📤 发送创建角色请求:`, JSON.stringify(createData, null, 2));
    this.ws.send(JSON.stringify(createData));
  }

  async testSelectCharacter () {
    console.log('\n🎯 步骤5: 选择角色...');
    if (this.characters.length === 0) {
      console.log('⚠️ 没有可选择的角色');
      this.addTestResult('选择角色', false, '没有可用角色');
      return;
    }

    return new Promise((resolve) => {
      if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
        this.addTestResult('选择角色', false, 'WebSocket未连接');
        resolve();
        return;
      }

      const targetCharacter = this.characters[0];
      this.originalCharacterName = targetCharacter.name;

      const responseHandler = (data) => {
        try {
          const message = JSON.parse(data.toString());
          if (message.act_id === 4) {
            this.ws.removeListener('message', responseHandler);

            if (message.code === 0) {
              this.selectedCharacter = targetCharacter;
              console.log(`✅ 角色选择成功: ${targetCharacter.name} (ID: ${targetCharacter.id})`);
              this.addTestResult('选择角色', true, `选择角色: ${targetCharacter.name}`);
              setTimeout(() => resolve(), 2000);
            } else {
              console.log(`❌ 角色选择失败: ${message.msg || '未知错误'}`);
              this.addTestResult('选择角色', false, message.msg || '选择失败');
              resolve();
            }
          }
        } catch (error) {
          this.ws.removeListener('message', responseHandler);
          this.addTestResult('选择角色', false, '响应解析失败');
          resolve();
        }
      };

      this.ws.on('message', responseHandler);
      this.ws.send(JSON.stringify({
        c: 4,
        d: { characterId: targetCharacter.id }
      }));

      setTimeout(() => {
        this.ws.removeListener('message', responseHandler);
        this.addTestResult('选择角色', false, '请求超时');
        resolve();
      }, 10000);
    });
  }

  async testCode1908NormalRename () {
    console.log('\n✏️ 步骤6: 测试1908接口 - 正常改名（需要改名卡）...');
    if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
      this.addTestResult('1908接口测试(正常改名)', false, 'WebSocket未连接');
      return;
    }

    return new Promise((resolve) => {
      let responseReceived = false;

      const responseHandler = (data) => {
        try {
          const message = JSON.parse(data.toString());
          if (message.act_id === 1908) {
            this.ws.removeListener('message', responseHandler);
            responseReceived = true;

            if (message.code === 0) {
              console.log('✅ 1908接口调用成功 - 改名成功');
              console.log(`✏️ 新名称: ${message.data?.name || '未知'}`);
              console.log(`💬 成功消息: ${message.msg || '无'}`);

              if (message.data && typeof message.data === 'object' && message.data.name) {
                console.log('✅ 基础数据结构验证通过');
                this.addTestResult('1908接口测试(正常改名)', true, `改名成功: ${message.data.name}`);
              } else {
                console.log('❌ 基础数据结构验证失败');
                this.addTestResult('1908接口测试(正常改名)', false, '返回数据格式错误');
              }
            } else {
              console.log(`❌ 1908接口调用失败: ${message.msg || '未知错误'}`);
              this.addTestResult('1908接口测试(正常改名)', false, message.msg || '调用失败');
            }
            resolve();
          }
        } catch (error) {
          console.error('❌ 1908接口响应解析失败:', error.message);
          this.ws.removeListener('message', responseHandler);
          this.addTestResult('1908接口测试(正常改名)', false, '响应解析失败');
          resolve();
        }
      };

      this.ws.on('message', responseHandler);

      const testName = `测试改名_${Date.now()}`;
      const requestData = {
        c: 1908,
        d: { name: testName }
      };

      console.log(`📤 发送1908请求(正常改名):`, JSON.stringify(requestData, null, 2));
      this.ws.send(JSON.stringify(requestData));

      setTimeout(() => {
        if (!responseReceived) {
          this.ws.removeListener('message', responseHandler);
          this.addTestResult('1908接口测试(正常改名)', false, '请求超时');
          resolve();
        }
      }, 10000);
    });
  }

  async testCode1908NameWithSpace () {
    console.log('\n✏️ 步骤7: 测试1908接口 - 名称包含空格（应该失败）...');
    if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
      this.addTestResult('1908接口测试(名称包含空格)', false, 'WebSocket未连接');
      return;
    }

    return new Promise((resolve) => {
      let responseReceived = false;

      const responseHandler = (data) => {
        try {
          const message = JSON.parse(data.toString());
          if (message.act_id === 1908) {
            this.ws.removeListener('message', responseHandler);
            responseReceived = true;

            if (message.code === -1) {
              console.log('✅ 1908接口调用成功 - 正确返回错误信息');
              console.log(`❌ 错误信息: ${message.msg || '未知错误'}`);

              if (message.msg && (message.msg.includes('空格') || message.msg.includes('不能包含'))) {
                console.log('✅ 错误处理验证通过');
                this.addTestResult('1908接口测试(名称包含空格)', true, '正确返回错误信息');
              } else {
                console.log('⚠️ 错误处理验证失败');
                this.addTestResult('1908接口测试(名称包含空格)', false, '错误信息格式不正确');
              }
            } else {
              console.log(`⚠️ 1908接口返回成功，但应该返回错误: ${message.code}`);
              this.addTestResult('1908接口测试(名称包含空格)', false, '应该返回错误但返回成功');
            }
            resolve();
          }
        } catch (error) {
          console.error('❌ 1908接口响应解析失败:', error.message);
          this.ws.removeListener('message', responseHandler);
          this.addTestResult('1908接口测试(名称包含空格)', false, '响应解析失败');
          resolve();
        }
      };

      this.ws.on('message', responseHandler);

      const requestData = {
        c: 1908,
        d: { name: '测试 改名' }
      };

      console.log(`📤 发送1908请求(名称包含空格):`, JSON.stringify(requestData, null, 2));
      this.ws.send(JSON.stringify(requestData));

      setTimeout(() => {
        if (!responseReceived) {
          this.ws.removeListener('message', responseHandler);
          this.addTestResult('1908接口测试(名称包含空格)', false, '请求超时');
          resolve();
        }
      }, 10000);
    });
  }

  async testCode1908EmptyName () {
    console.log('\n✏️ 步骤8: 测试1908接口 - 空名称（应该失败）...');
    if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
      this.addTestResult('1908接口测试(空名称)', false, 'WebSocket未连接');
      return;
    }

    return new Promise((resolve) => {
      let responseReceived = false;

      const responseHandler = (data) => {
        try {
          const message = JSON.parse(data.toString());
          if (message.act_id === 1908) {
            this.ws.removeListener('message', responseHandler);
            responseReceived = true;

            if (message.code === -1) {
              console.log('✅ 1908接口调用成功 - 正确返回错误信息');
              console.log(`❌ 错误信息: ${message.msg || '未知错误'}`);

              if (message.msg && (message.msg.includes('不能为空') || message.msg.includes('无效'))) {
                console.log('✅ 错误处理验证通过');
                this.addTestResult('1908接口测试(空名称)', true, '正确返回错误信息');
              } else {
                console.log('⚠️ 错误处理验证失败');
                this.addTestResult('1908接口测试(空名称)', false, '错误信息格式不正确');
              }
            } else {
              console.log(`⚠️ 1908接口返回成功，但应该返回错误: ${message.code}`);
              this.addTestResult('1908接口测试(空名称)', false, '应该返回错误但返回成功');
            }
            resolve();
          }
        } catch (error) {
          console.error('❌ 1908接口响应解析失败:', error.message);
          this.ws.removeListener('message', responseHandler);
          this.addTestResult('1908接口测试(空名称)', false, '响应解析失败');
          resolve();
        }
      };

      this.ws.on('message', responseHandler);

      const requestData = {
        c: 1908,
        d: { name: '' }
      };

      console.log(`📤 发送1908请求(空名称):`, JSON.stringify(requestData, null, 2));
      this.ws.send(JSON.stringify(requestData));

      setTimeout(() => {
        if (!responseReceived) {
          this.ws.removeListener('message', responseHandler);
          this.addTestResult('1908接口测试(空名称)', false, '请求超时');
          resolve();
        }
      }, 10000);
    });
  }

  async testCode1908DuplicateName () {
    console.log('\n✏️ 步骤9: 测试1908接口 - 重复名称（应该失败）...');
    if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
      this.addTestResult('1908接口测试(重复名称)', false, 'WebSocket未连接');
      return;
    }

    return new Promise((resolve) => {
      let responseReceived = false;

      const responseHandler = (data) => {
        try {
          const message = JSON.parse(data.toString());
          if (message.act_id === 1908) {
            this.ws.removeListener('message', responseHandler);
            responseReceived = true;

            if (message.code === -1) {
              console.log('✅ 1908接口调用成功 - 正确返回错误信息');
              console.log(`❌ 错误信息: ${message.msg || '未知错误'}`);

              if (message.msg && (message.msg.includes('已被使用') || message.msg.includes('重复') || message.msg.includes('已存在'))) {
                console.log('✅ 错误处理验证通过');
                this.addTestResult('1908接口测试(重复名称)', true, '正确返回错误信息');
              } else {
                console.log('⚠️ 错误处理验证失败');
                this.addTestResult('1908接口测试(重复名称)', false, '错误信息格式不正确');
              }
            } else {
              console.log(`⚠️ 1908接口返回成功，但应该返回错误: ${message.code}`);
              this.addTestResult('1908接口测试(重复名称)', false, '应该返回错误但返回成功');
            }
            resolve();
          }
        } catch (error) {
          console.error('❌ 1908接口响应解析失败:', error.message);
          this.ws.removeListener('message', responseHandler);
          this.addTestResult('1908接口测试(重复名称)', false, '响应解析失败');
          resolve();
        }
      };

      this.ws.on('message', responseHandler);

      const requestData = {
        c: 1908,
        d: { name: this.originalCharacterName }
      };

      console.log(`📤 发送1908请求(重复名称):`, JSON.stringify(requestData, null, 2));
      this.ws.send(JSON.stringify(requestData));

      setTimeout(() => {
        if (!responseReceived) {
          this.ws.removeListener('message', responseHandler);
          this.addTestResult('1908接口测试(重复名称)', false, '请求超时');
          resolve();
        }
      }, 10000);
    });
  }

  async testCode1908NoRenameCard () {
    console.log('\n✏️ 步骤10: 测试1908接口 - 没有改名卡（应该失败）...');
    if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
      this.addTestResult('1908接口测试(没有改名卡)', false, 'WebSocket未连接');
      return;
    }

    return new Promise((resolve) => {
      let responseReceived = false;

      const responseHandler = (data) => {
        try {
          const message = JSON.parse(data.toString());
          if (message.act_id === 1908) {
            this.ws.removeListener('message', responseHandler);
            responseReceived = true;

            if (message.code === -1) {
              console.log('✅ 1908接口调用成功 - 正确返回错误信息');
              console.log(`❌ 错误信息: ${message.msg || '未知错误'}`);

              if (message.msg && (message.msg.includes('改名卡') || message.msg.includes('无法改名'))) {
                console.log('✅ 错误处理验证通过');
                this.addTestResult('1908接口测试(没有改名卡)', true, '正确返回错误信息');
              } else {
                console.log('⚠️ 错误处理验证失败');
                this.addTestResult('1908接口测试(没有改名卡)', false, '错误信息格式不正确');
              }
            } else {
              console.log(`⚠️ 1908接口返回成功，但应该返回错误: ${message.code}`);
              this.addTestResult('1908接口测试(没有改名卡)', false, '应该返回错误但返回成功');
            }
            resolve();
          }
        } catch (error) {
          console.error('❌ 1908接口响应解析失败:', error.message);
          this.ws.removeListener('message', responseHandler);
          this.addTestResult('1908接口测试(没有改名卡)', false, '响应解析失败');
          resolve();
        }
      };

      this.ws.on('message', responseHandler);

      const requestData = {
        c: 1908,
        d: { name: '测试改名卡验证' }
      };

      console.log(`📤 发送1908请求(没有改名卡):`, JSON.stringify(requestData, null, 2));
      this.ws.send(JSON.stringify(requestData));

      setTimeout(() => {
        if (!responseReceived) {
          this.ws.removeListener('message', responseHandler);
          this.addTestResult('1908接口测试(没有改名卡)', false, '请求超时');
          resolve();
        }
      }, 10000);
    });
  }

  async validateRenameCardConsumption () {
    console.log('\n🔍 步骤11: 验证改名卡消耗...');

    if (this.renameResults.length === 0) {
      console.log('⚠️ 没有改名结果可供验证');
      this.addTestResult('改名卡消耗验证', false, '无数据可供验证');
      return;
    }

    console.log(`📊 开始验证改名卡消耗逻辑...`);

    const successfulRenames = this.renameResults.filter(result => result.code === 0);
    const failedRenames = this.renameResults.filter(result => result.code === -1);

    console.log(`✅ 成功改名次数: ${successfulRenames.length}`);
    console.log(`❌ 失败改名次数: ${failedRenames.length}`);

    if (successfulRenames.length > 0) {
      const successResult = successfulRenames[0];
      if (successResult.data && successResult.data.name && successResult.msg === '改名成功') {
        console.log('✅ 成功改名响应格式验证通过');
        this.addTestResult('改名卡消耗验证', true, '成功改名响应格式正确');
      } else {
        console.log('❌ 成功改名响应格式验证失败');
        this.addTestResult('改名卡消耗验证', false, '成功改名响应格式错误');
      }
    }

    if (failedRenames.length > 0) {
      const hasValidErrorMessages = failedRenames.every(result =>
        result.msg && result.msg.length > 0
      );

      if (hasValidErrorMessages) {
        console.log('✅ 失败改名错误信息验证通过');
        this.addTestResult('改名卡消耗验证', true, '失败改名错误信息完整');
      } else {
        console.log('❌ 失败改名错误信息验证失败');
        this.addTestResult('改名卡消耗验证', false, '失败改名错误信息不完整');
      }
    }

    const hasConsistentResponses = this.renameResults.every(result =>
      (result.code === 0 && result.data && result.data.name) ||
      (result.code === -1 && result.msg)
    );

    if (hasConsistentResponses) {
      console.log('✅ 事务控制验证通过 - 响应格式一致');
      this.addTestResult('改名卡消耗验证', true, '事务控制响应一致');
    } else {
      console.log('❌ 事务控制验证失败 - 响应格式不一致');
      this.addTestResult('改名卡消耗验证', false, '事务控制响应不一致');
    }
  }

  async testDisconnect () {
    console.log('\n🔌 步骤12: 断开WebSocket连接...');
    if (this.ws) {
      this.ws.close();
    }
    this.addTestResult('断开连接', true, '连接已断开');
  }

  addTestResult (testName, success, message) {
    this.testResults.push({
      test: testName,
      success: success,
      message: message,
      timestamp: new Date().toISOString()
    });
  }

  printTestResults () {
    console.log('\n📊 测试结果汇总:');
    console.log('='.repeat(50));

    let successCount = 0;
    let totalCount = this.testResults.length;

    this.testResults.forEach((result, index) => {
      const status = result.success ? '✅' : '❌';
      console.log(`${index + 1}. ${status} ${result.test}: ${result.message}`);
      if (result.success) successCount++;
    });

    console.log('='.repeat(50));
    console.log(`总计: ${successCount}/${totalCount} 项测试通过`);

    if (successCount === totalCount) {
      console.log('🎉 所有测试通过！');
    } else {
      console.log('⚠️  部分测试失败，请检查日志');
    }

    if (this.renameResults.length > 0) {
      console.log('\n📋 改名功能测试分析:');
      console.log('='.repeat(50));
      console.log(`总测试次数: ${this.renameResults.length}`);

      const successCount = this.renameResults.filter(r => r.code === 0).length;
      const failCount = this.renameResults.filter(r => r.code === -1).length;

      console.log(`成功次数: ${successCount}`);
      console.log(`失败次数: ${failCount}`);
      console.log(`成功率: ${((successCount / this.renameResults.length) * 100).toFixed(1)}%`);

      if (failCount > 0) {
        console.log('\n错误类型分析:');
        const errorTypes = {};
        this.renameResults.forEach(result => {
          if (result.code === -1 && result.msg) {
            const errorKey = result.msg.includes('空格') ? '名称包含空格' :
              result.msg.includes('已被使用') ? '名称重复' :
                result.msg.includes('改名卡') ? '缺少改名卡' :
                  result.msg.includes('不能为空') ? '名称为空' : '其他错误';
            errorTypes[errorKey] = (errorTypes[errorKey] || 0) + 1;
          }
        });

        Object.entries(errorTypes).forEach(([type, count]) => {
          console.log(`  ${type}: ${count}次`);
        });
      }
    }
  }

  async makeHttpRequest (path, method = 'GET', data = null) {
    return new Promise((resolve, reject) => {
      const options = {
        hostname: CONFIG.server.host,
        port: CONFIG.server.port,
        path: path,
        method: method,
        headers: {
          'Content-Type': 'application/json',
        }
      };

      if (data) {
        const postData = JSON.stringify(data);
        options.headers['Content-Length'] = Buffer.byteLength(postData);
      }

      const req = http.request(options, (res) => {
        let body = '';

        res.on('data', (chunk) => {
          body += chunk;
        });

        res.on('end', () => {
          try {
            const responseData = JSON.parse(body);
            if (res.statusCode >= 200 && res.statusCode < 300) {
              resolve(responseData);
            } else {
              reject(new Error(`HTTP ${res.statusCode}: ${responseData.message || body}`));
            }
          } catch (error) {
            if (res.statusCode >= 200 && res.statusCode < 300) {
              resolve(body);
            } else {
              reject(new Error(`HTTP ${res.statusCode}: ${body}`));
            }
          }
        });
      });

      req.on('error', (error) => {
        reject(error);
      });

      if (data) {
        req.write(JSON.stringify(data));
      }

      req.end();
    });
  }

  async delay (ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
  }
}

async function main () {
  const tester = new Code1908Tester();
  await tester.runTest();
}

if (require.main === module) {
  main().catch((error) => {
    console.error('💥 测试脚本执行失败:', error.message);
    process.exit(1);
  });
}

module.exports = Code1908Tester; 